"""清理工具模块"""
import shutil
from pathlib import Path
from .logger import get_logger

class Cleaner:
    """清理编译过程中产生的中间文件"""
    
    def __init__(self, verbose: bool = False):
        self.logger = get_logger("cleaner", verbose)
    
    def remove_file(self, file_path: Path) -> bool:
        """删除单个文件"""
        if file_path.exists() and file_path.is_file():
            try:
                file_path.unlink()
                self.logger.info(f"已删除中间文件: {file_path.name}")
                return True
            except Exception as e:
                self.logger.warning(f"删除文件 {file_path.name} 失败: {str(e)}")
        return False
    
    def remove_directory(self, dir_path: Path) -> bool:
        """删除目录"""
        if dir_path.exists() and dir_path.is_dir():
            try:
                shutil.rmtree(dir_path)
                self.logger.info(f"已删除目录: {dir_path.name}/")
                return True
            except Exception as e:
                self.logger.warning(f"删除目录 {dir_path.name} 失败: {str(e)}")
        return False
    
    def clean_compilation_files(self, module_name: str, working_dir: Path):
        """清理编译相关文件"""
        # 删除C文件
        self.remove_file(working_dir / f"{module_name}.c")
        
        # 删除build目录
        self.remove_directory(working_dir / "build")
        
        # 删除可能的临时文件
        for tmp_file in working_dir.glob(f"{module_name}.*.so"):
            if not tmp_file.name.endswith(".so"):
                self.remove_file(tmp_file)
